package com.example.photography.fragment.home;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.photography.R;
import com.example.photography.adapter.home_recommed.RecommedAdapter;
import com.example.photography.bean.Home_RecommendBean;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseFragment;
import com.example.photography.util.UIUtils;
import com.example.photography.util.Util;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class Home_recommend extends BaseFragment {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private boolean sign;
    private Home_RecommendBean home_recommendBean;
    private RecommedAdapter recommedAdapter;

    @Override
    protected RequestParams getParams() {
        return null;
    }

    @Override
    protected String getUrl() {
        return null;
    }

    @Override
    protected void initData(String content) {
        content = Util.getJson(getActivity(), "home_recommed.json");
//        content = Util.getJson(getActivity(),"store_home.json");

        if (TextUtils.isEmpty(content)) {//数据为空
            return;
        }
        JSONObject jsonObject = JSON.parseObject(content);
        int status = jsonObject.getInteger("code");
        if (status == 202) {
            String data = jsonObject.getString("data");
            //封装转json数据
            home_recommendBean = JSONObject.parseObject(data, Home_RecommendBean.class);
            initView();
        } else {
            // TODO: 2021/5/2 加没数据的判断
        }


        /**
         * 下拉刷新
         */
        refreshLayout.setRefreshHeader(new ClassicsHeader(UIUtils.getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(UIUtils.getContext()));
        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(UIUtils.getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                });
                sign = false;
                sendAsyncHttpClient();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //todo 有时刷新失败
                        refreshlayout.finishRefresh(sign);//传入false表示刷新失败
                    }
                }, 2000);

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
    }


    private void initView() {
        recommedAdapter = new RecommedAdapter(getActivity(), home_recommendBean);
//        /**
//         * 获取轮转图片数据
//         */
//        images = homeRecommendData.getImageArr();
//        /**
//         * 获取listview数据
//         */
//        list_data = homeRecommendData.getList_data();
//
//        recommedAdapter = new RecommedAdapter(images, list_data, getActivity()) {
//            @Override
//            public void to_product_content(int art_id) {
//                Intent intent = new Intent(mContext, Product_Content.class);
//                Bundle bundle = new Bundle();
//                bundle.putInt("art_id", art_id);
//                intent.putExtra("data", bundle);
//                startActivity(intent);
//            }
//
//            @Override
//            public void to_User_home() {
//                Intent intent = new Intent(mContext, My_Activity.class);
//                startActivity(intent);
//            }
//        };
        rvProduct.setAdapter(recommedAdapter);
        //设置布局管理者
        rvProduct.setLayoutManager(new GridLayoutManager(getActivity(),1));

    }

    private void sendAsyncHttpClient() {
        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AsyncHttpClient client = new AsyncHttpClient();
                client.post(AppNetConfig.home_recommed, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        //解析json数据
                        String jsonData = new String(responseBody);
                        if (!jsonData.equals("")) {

                            handler.sendEmptyMessageDelayed(1, 0);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Util.show(getActivity(), "网络请求失败~");
                    }
                });
            }
        }, 0);
    }


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    sign = true;
                    //刷新适配器
//                    recommedAdapter.refresh(images, list_data);
                    break;
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.home_recommend;
    }
}
